import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, QueryList, ViewChild, ViewChildren } from "@angular/core";
import { GameLogic } from "../../game/core/game-logic";
import { GameEngine } from "../../game/core/game-engine";
import { DummyGame } from "../../game/inst/dummy-game";

@Component({
	selector: 'app-index',
	templateUrl: 'index.page.html',
	styleUrls: ['index.page.scss'],
})
export class IndexPage implements OnInit, AfterViewInit, OnDestroy {

	@ViewChild("gameContainer", { static: true }) gameContainer?: ElementRef<HTMLDivElement>;
	@ViewChildren("touchButtons") touchButtons?: QueryList<ElementRef<HTMLDivElement>>;

	protected hasTouchEvent: boolean = ('ontouchstart' in window);
	private logic?: GameLogic;
	private engine?: GameEngine;

	constructor() {
	}

	ngOnInit(): void {
	}

	ngAfterViewInit(): void {
		this.initGame();
	}

	ngOnDestroy(): void {
		this.engine?.destroy();
	}

	initGame(): void {
		let dom = this.gameContainer?.nativeElement;
		if (dom == null || this.touchButtons == null || this.touchButtons.length == 0 ||
			this.gameContainer?.nativeElement.clientWidth == 0 ||
			this.gameContainer?.nativeElement.clientHeight == 0) {
			setTimeout(() => {
				this.initGame();
			}, 25)
		} else {
			let option = {
				seed: 114514,
				start: { x: 5000, y: 10, z: 5000 },
				bounds: {
					topLeft: {
						x: 1000,
						z: 1000
					},
					bottomRight: {
						x: 11000,
						z: 11000
					},
				},
				visualField: 36,
				frameUpdateBlock: 12,
			}
			let touchButtons = [];
			for (let i = 0; i < this.touchButtons.length; i++) {
				let button = this.touchButtons.get(i);
				if (button != null) {
					touchButtons.push(button.nativeElement);
				}
			}
			this.logic = new DummyGame(option);
			this.engine = new GameEngine(dom, touchButtons, this.logic);
		}
	}

}
